package es.onlysolutions.gs.web.controller;

import com.google.gdata.data.youtube.VideoEntry;
import es.onlysolutions.arq.core.mvc.command.AbstractCommandBean;
import es.onlysolutions.gs.comm.facade.VideoFacade;
import es.onlysolutions.gs.comm.utils.VideoUtils;
import es.onlysolutions.gs.web.beanObject.VideoObject;
import es.onlysolutions.gs.web.commandBean.SearchVideoBean;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Controller to search directly from YouTube or from the community favourites.
 */
public class SearchVideoController extends GSController
{
    private VideoFacade videoFacade;

    /**
     * Query string param.
     */
    public static final String REQUEST_QUERY_STRING = "queryString";

    public void setVideoFacade(VideoFacade videoFacade)
    {
        this.videoFacade = videoFacade;
    }

    protected AbstractCommandBean loadPage(HttpServletRequest httpServletRequest) throws Exception
    {
        return null;
    }

    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception
    {
        SearchVideoBean bean = (SearchVideoBean) command;

        /**
         * Extract the queryString from the requests if not mapped to the bean.
         */
        String queryString = bean.getQueryString();

        if( queryString != null && queryString.length() > 0 )
        {
            List<VideoEntry> entries = videoFacade.getVideoResults( bean.getQueryString() );
            List<VideoObject> videos = new ArrayList<VideoObject>(entries.size());

            for (VideoEntry videoEntry : entries)
            {
                VideoObject vo = new VideoObject();
                vo.setTitle(videoEntry.getTitle().getPlainText());
                vo.setDescription(videoEntry.getPlainTextContent());
                vo.setUrlImage( VideoUtils.getImageUrl(videoEntry) );
                vo.setYouTubeId( VideoUtils.extractYouTubeId(videoEntry) );

                videos.add(vo);
            }

            bean.setVideos(videos);
        }


        return new ModelAndView( getSuccessView(), getCommandName(), bean );
    }

}
